package com.xiaoq.users.emchat.service;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.xiaoq.users.emchat.api.ChatGroupAPI;
import com.xiaoq.users.emchat.comm.ClientContext;
import com.xiaoq.users.emchat.comm.EasemobRestAPIFactory;
import com.xiaoq.users.emchat.comm.body.ChatGroupBody;
import com.xiaoq.users.emchat.comm.wrapper.BodyWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author xinpeng created on 2016/12/8-下午3:35.
 */
@Service
public class EasemobChatGroupService {

    private static final Logger logger = LoggerFactory.getLogger(EasemobChatGroupService.class);


    public String createChatGroup(String groupName,long maxusersOfActivity,String organizerIdOfActivity){

        logger.debug("groupName = "+groupName);

        logger.debug("maxusersOfActivity = "+maxusersOfActivity);

        logger.debug("organizerIdOfActivity = "+organizerIdOfActivity);

        BodyWrapper chatGroupBody = new ChatGroupBody(groupName,groupName,true,maxusersOfActivity,false,organizerIdOfActivity);

        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();

        ChatGroupAPI chatGroupAPI=  (ChatGroupAPI)factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);

        Object obj = chatGroupAPI.createChatGroup(chatGroupBody);

        String responseStr = obj.toString();

        logger.debug("responseStr = "+responseStr);

        String jsonStr = responseStr.substring(26);

        logger.debug("jsonStr:"+jsonStr);

        Gson gs = new  Gson();
        Map map = gs.fromJson(jsonStr, Map.class);
        Object data  =  map.get("data");
        logger.debug("data =  "+data);
        LinkedTreeMap groupMap = (LinkedTreeMap)data;
        String groupId = (String)groupMap.get("groupid");
        logger.debug("groupId = "+ groupId);

        return groupId;
    }
}
